const bcrypt = require('bcrypt')
const userModel = require('../models/users.model')
const HttpException = require('../utils/HttpException')
const logger = require('../utils/logger')
class UserService {
  users = userModel
  async findAll ({ page = 1, pageSize = 100, username, role }) {
    const query = {
      deleted: false
    }
    if (username) {
      query.username = { $regex: new RegExp(username, 'i') }
    }
    if (role) {
      query.role = role
    }
    const sort = {
      createdDate: -1
    }
    page = parseInt(page) || 1
    const limit = parseInt(pageSize) || 100
    const skip = (page - 1) * (limit)
    const data = await this.users.find(query).sort(sort).skip(skip).limit(limit)
    const totalSize = await this.users.countDocuments(query)
    return {
      data,
      totalSize
    }
  }
  findOne (id) {
    return this.users.find({ deleted: false, _id: id })
  }
  async updateOne (id, data) {
    if (data.newPassword) {
      // todo compare old password
      const user = await this.users.findById({ _id: id })
      const isPasswordMatching = await bcrypt.compare(data.password, user.password)
      if (isPasswordMatching) {
        data.password = await bcrypt.hash(data.newPassword, 10)
      } else {
        throw new HttpException(409, `password is not matching`)
      }
    } else {
      delete data.password
    }
    return this.users.findOneAndUpdate({ _id: id }, data)
  }
  deleteOne (id) {
    return this.users.findOneAndRemove({ _id: id })
  }
}

module.exports = UserService